package com.sunshine.demo.util;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
//import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;

public class HttpUtil {
	
	private static final String APPLICATION_JSON = "application/json;charset=utf-8";
    
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json;charset=utf-8";
    
	public static HttpResponse httpPostToResponse(String url, String json) throws Exception {
        // 将JSON进行UTF-8编码,以便传输中文
        json = URLEncoder.encode(json, HTTP.UTF_8);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient = wrapClient(httpClient);
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
        
        StringEntity se = new StringEntity(json);
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
        httpPost.setEntity(se);
        HttpResponse response = httpClient.execute(httpPost);
        return response;
    }
	
	public static DefaultHttpClient wrapClient(DefaultHttpClient base) {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain, String authType) 
						throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] chain, String authType) 
						throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx);
			ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ClientConnectionManager ccm = (ClientConnectionManager) base.getConnectionManager();
			SchemeRegistry sr = ccm.getSchemeRegistry();
			// 设置要使用的端口，默认是443
			sr.register(new Scheme("https", ssf, 443));
			return new DefaultHttpClient(ccm);
		} catch (Exception ex) {
			System.out.println("wrapClient failed:" + ex.getMessage());
			return null;
		}
	}
	
	/**
	 * 发送post请求并打印参数
	 * @param url
	 * @param json
	 * @return
	 * @throws Exception
	 */
	public static String httpPostToJSON(String url, String json) throws Exception {
		System.out.println("请求服务器 123json===>" + json); 
        HttpResponse response = httpPostToResponse(url, json);
        String jsonStr = EntityUtils.toString(response.getEntity());
        System.out.println("收到服务器 321json===>" + jsonStr); 
        return jsonStr;
    }
	

	/**
	 * 发送get请求获取返回的字符串
	 * @param url
	 * @param host
	 * @param referer 
	 * @param cookie
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String getGetResult(String url, String host, String referer, String cookies) {
		
		DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient = wrapClient(httpClient);
        HttpGet request = new HttpGet(url);
        request.addHeader(new BasicHeader("Host", host));
		request.addHeader(new BasicHeader("Referer",referer));
		request.addHeader(new BasicHeader("Cookie",cookies));
		
        String jsonStr="";
		try {
			HttpResponse response = httpClient.execute(request);
			jsonStr = EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		}
        return jsonStr;
	}
	
	public static void main(String[] args) throws Exception {
		String json = "{\"method\":\"getTrades\",\"ver\":\"1.0\",\"channelId\":\"1\",\"params\":{\"idNo\":\"230881198405242210\",\"userIdResource\":\"986851856913\",\"startDate\":\"2015-09-01 00:00:01\",\"endDate\":\"2015-09-01 12:59:59\"}}";
		
		String url = "https://59.108.127.184:8090/ygylserver/execute.do";
		System.out.println(httpPostToJSON(url, json));
	}
	
}
